import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Form, Button, ErrorBlock, Picker, Dialog, Input } from "antd-mobile";
import { callNativeApi, createAction } from "@common/utils";
import { BARCODE_PARSER } from "@common/constants";
import { getSelectedWarehouses } from "@store/user-profile/selectors";
import {
  PUSH_PAGE_STACK,
  SET_PAGE_TITLE,
  SET_SCAN_DATA,
} from "@store/global-state/action-types";

const WarehouseQuery = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const warehouseItems = useSelector((state) => getSelectedWarehouses(state));
  const [form] = Form.useForm();
  const [visible, setVisible] = useState();
  const scandata = useSelector((state) => state.globalState.scandata);

  const switchPage = (subPath, barcode) => {
    let path = `/app/warehouse-query/${subPath}?warehouseId=${form.getFieldValue(
      "warehouseId"
    )}&barcode=${barcode}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  useEffect(() => {
    dispatch(createAction(SET_PAGE_TITLE, "库内查询"));
    return () => dispatch(createAction(SET_SCAN_DATA, null));
  }, []);

  useEffect(() => {
    if (!warehouseItems || warehouseItems[0].length === 0) {
      Dialog.alert({ content: "请先设置默认使用场景!" });
    } else {
      let warehouse = warehouseItems[0][0];
      form.setFields([
        { name: "warehouseId", value: warehouse.value },
        { name: "warehouseName", value: warehouse.label },
      ]);
    }
  }, [warehouseItems]);

  useEffect(() => {
    if (scandata) {
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: { barcode: scandata, bizType: "QUERY" },
        needNonce: false,
      })
        .then((resp) => {
          let result = resp.data ? resp.data.payload : resp.payload;
          if (result.ruleType === "ITEM") {
            // 物料码
            switchPage("item-info", scandata);
          } else if (result.ruleType === "LOCATION") {
            // 库位码
            switchPage("loc-info", scandata);
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => console.log(error));
    }
  }, [scandata]);

  const setWarehouse = ({ items }) => {
    form.setFields([
      { name: "warehouseId", value: items[0].value },
      { name: "warehouseName", value: items[0].label },
    ]);
  };

  return (
    <div style={{ marginTop: "45px", marginBottom: "65px" }}>
      <Form form={form} mode="card">
        <Form.Header>选择仓库</Form.Header>
        <Form.Item
          name="warehouseName"
          label="仓库"
          extra={
            <Button
              size="small"
              color="primary"
              fill="outline"
              onClick={() => setVisible(true)}
            >
              选择
            </Button>
          }
        >
          <Input readOnly />
        </Form.Item>
        <Form.Header />
        <Form.Header>条码扫描</Form.Header>
        <ErrorBlock status="empty" title="请扫描物料或库位码" description="" />
      </Form>
      <Picker
        columns={warehouseItems}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
        onConfirm={(_, ext) => setWarehouse(ext)}
      />
    </div>
  );
};

export default WarehouseQuery;
